#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <string>
#include <unistd.h>

#define BUFFER_SIZE 1024

void Useage(const char* proc)
{
    printf("Useage error\n\t %s IP Port\n", proc);
}

int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Useage(argv[0]);
        return 1;
    }

    // 创建套接字信息
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "client sock error" << std::endl;
        exit(2);
    }

    std::string IP = argv[1];
    uint16_t port = std::stoi(argv[2]);

    struct sockaddr_in serverAddr;
    memset(&serverAddr, 0, sizeof(struct sockaddr_in));
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(port);
    serverAddr.sin_addr.s_addr = inet_addr(IP.c_str());

    // 向服务器发起连接请求
    int n = connect(sockfd, (struct sockaddr*)&serverAddr, sizeof(struct sockaddr_in));
    if(n < 0)
    {
        printf("client connect error, %s, %d", strerror(errno), errno);
        exit(3);
    }

    char buffer[BUFFER_SIZE];
    while(true)
    {
        std::cout << "Please Enter# ";
        std::string message;
        std::getline(std::cin, message);
        if(message.empty()) continue;

        // 发送消息
        ssize_t sendBytes = send(sockfd, message.c_str(), message.size(), 0);
        if(sendBytes > 0)
        {
            // 接收消息
            ssize_t receiveBytes = recv(sockfd, buffer, BUFFER_SIZE - 1, 0);
            if(receiveBytes < 0)
            {
                printf("client receive error, %s, %d", strerror(errno), errno);
                break;
            }
            else
            {
                buffer[receiveBytes] = 0;
                std::cout << buffer << std::endl;
            }
        }
        else if(sendBytes < 0)
        {
            printf("client send error, %s, %d", strerror(errno), errno);
            break;
        }
        else
            break;
    }

    close(sockfd);
    return 0;
}